<!-- prettier-ignore -->
<template>
  <div class="data-assembly">
    <div class="resource-catalog">
      <div>
        <p>块数据目录</p>
        <wp-scrollbar :max-height="700">
          <el-tree ref="catalogueTree" :data="catalogueTree" :indent="30" default-expand-all show-checkbox @check="cataCheck">
            <div slot-scope="{ node, data }" class="custom-tree-node" style="display: flex;align-items: center">
              <img v-if="(data.children && data.children.length > 0) || node.level === 1" :src="require('@/assets/images/dataAssembly/文件夹.png')" alt="">
              <span>{{ node.label }}</span>
            </div>
          </el-tree>
        </wp-scrollbar>
      </div>
      <div>
        <el-button type="primary">数据导入</el-button>
        <el-button type="primary">添加根节点</el-button>
      </div>
    </div>
    <div class="map-box">
      <div class="condition-box">
        <!--<el-cascader ref="cascader" v-model="taskRange" :props="cityProps" size="small" style="width: 300px" @change="cityChange">-->
        <!--</el-cascader>-->
        <district-select v-model="taskRange" style="width: 300px"></district-select>
        <el-button type="primary" @click="drawRange">框选范围</el-button>
        <div v-if="showCommunity" class="region-select">
          <div v-if="step === 1">
            <p>可视区域内为您找到5个管理单元</p>
            <wp-scrollbar :max-height="400">
              <el-tree ref="communityTree" :data="communityTree" :default-checked-keys="defaultChecked" default-expand-all node-key="label" show-checkbox @check="treeCheck"></el-tree>
            </wp-scrollbar>
          </div>
          <div v-if="step === 2">
            <p>可视区域内为您找到4个专题数据</p>
            <wp-scrollbar :max-height="400">
              <el-tree ref="thematicDataTree" :data="thematicDataTree" :default-checked-keys="thematicDefaultCheck" :expand-on-click-node="false" default-expand-all highlight-current node-key="label"  show-checkbox @check="checkChange">
                <div slot-scope="{ node, data }" class="custom-tree-node" style="display: flex;align-items: center">
                  <span>{{ node.label }}</span>
                  <img :src="require('@/assets/images/dataAssembly/筛选.png')" alt="" style="width: 14px" @click="setFiltering(data)">
                </div>
              </el-tree>
            </wp-scrollbar>
          </div>
          <div style="margin-top: 10px;text-align: right">
            <el-button v-if="step === 1" size="small" type="primary" @click="step++">下一步</el-button>
            <el-button v-if="step === 2" size="small" type="primary" @click="step--">上一步</el-button>
            <el-button v-if="step === 2" size="small" type="primary" @click="exportReport">导出</el-button>
            <el-button v-if="step === 2" size="small" type="primary" @click="publishShow = true">发布</el-button>
            <el-button size="small" type="primary">取消</el-button>
          </div>
        </div>
      </div>
      <cesium-map ref="cesiumRef" @mapFinish="cesiumFinish"></cesium-map>
      <div class="legend">
        <h3 style="text-align: center">图例</h3>
        <el-row :gutter="16">
          <el-col v-for="(item,index) in legendData" :key="index" :span="12">
            <div class="legend-item">
              <img :src="require(`@/assets/images/map/${item.img}`)" alt="">
              <span>{{item.label}}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <publish-dialog v-if="publishShow" :previewUrl="{otherLayers,cataLayers}" :rangeEntity="communityPrimitive" :show.sync="publishShow"></publish-dialog>
    <el-dialog :visible.sync="filterShow" title="设置筛选" width="50%">
      <el-form label-width="120px">
        <el-form-item label="筛选主题">
          <el-input v-model="filterForm.label"></el-input>
        </el-form-item>
        <el-form-item label="筛选条件">
          <el-row :gutter="16" type="flex">
            <el-col :span="8">
              <el-select v-model="filterFields" style="width: 100%">
                <el-option v-for="(item,index) in fieldOptions" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
            <el-col v-if="filterFields" :span="8">
              <el-select v-model="calculateSymbol" style="width: 100%">
                <el-option label="早于" value="<"></el-option>
                <el-option label="晚于" value=">"></el-option>
                <el-option label="等于" value="="></el-option>
              </el-select>
            </el-col>
            <el-col v-if="filterFields" :span="8">
              <el-date-picker v-model="filterYear" format="yyyy" placeholder="选择年份" style="width: 100%" type="year">
              </el-date-picker>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="filterShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addLabelLayer, addLayer, removeLayer} from '@/utils/map';

const FILTER_OBJ = {
  label:'',
  filter:''
}
import axios from 'axios'

import districtSelect from '@/views/oneCodeAccess/districtSelect.vue';
import cesiumMap from '@/components/cesiumMap/index.vue';
import publishDialog from '@/views/dataAssembly/publishDialog.vue';
import choseSq from '@/assets/chose_sq.json'
import Draw from '@/utils/cesiumFun';
export default {
  name: 'index',
  components:{cesiumMap,publishDialog,districtSelect},
  data(){
    return {
      legendData:[
        {
          img:'公交首末站.svg',
          label:'公交'
        },
        {
          img:'公园.svg',
          label:'公园'
        },
        {
          img:'九年一贯制学校.svg',
          label:'学校'
        },
        {
          img:'综合医院.svg',
          label:'医院'
        }
      ],
      filterYear:'',
      fieldOptions:[
        {
          value:'sex',
          label:'性别'
        },
        {
          value:'batch',
          label:'出生日期'
        },
        {
          value:'address',
          label:'住址'
        },
        {
          value:'phone',
          label:'联系电话'
        }
      ],
      filterFields:'',
      calculateSymbol:'=',
      thematicDefaultCheck:[],
      filterForm:JSON.parse(JSON.stringify(FILTER_OBJ)),
      filterShow: false,
      publishShow: false,
      step:1,
      taskRange:['黄州区','赤壁街道'],
      catalogueTree:[],
      // cityProps: {
      //   value: "name",
      //   label: "name",
      //   checkStrictly: true,
      //   children: "districts",
      //   lazy: true,
      //   lazyLoad: this.getCityProps,
      // },
      defaultChecked:['八一社区','青云社区','二机社区','宝塔社区','建新社区'],
      communityTree:[
        {
          label:'赤壁街道',
          children:[
            {
              label:'宝塔社区'
            },
            {
              label:'建新社区'
            },
            {
              label:'汉川门社区'
            },
            {
              label:'清源门社区'
            },
            {
              label:'青云社区'
            },
            {
              label:'二机社区'
            },
            {
              label:'一字门社区'
            },
            {
              label:'体育路社区'
            },
            {
              label:'东门社区'
            },
            {
              label:'毛纺社区'
            },
            {
              label:'有线社区'
            },
            {
              label:'八一社区'
            },
            {
              label:'江北社区'
            },
            {
              label:'大地社区'
            },
            {
              label:'印染社区'
            },
            {
              label:'惠民社区'
            },
            {
              label:'扬子江社区'
            },
            {
              label:'安居社区'
            },
            {
              label:'三清社区'
            },
            {
              label:'四海社区'
            },
            {
              label:'青砖湖社区'
            },
            {
              label:'赤壁社区'
            },
            {
              label:'龙王山社区'
            },
            {
              label:'潘家湾社区'
            },
            {
              label:'桐梓岗社区'
            },
            {
              label:'铝业社区'
            }
          ]
        }
      ],
      thematicDataTree:[],
      showCommunity:false,
      previewUrl:{
        layer: "",
        label:""
      }
    }
  },
  created(){
    this.catalogueTree = window.treeData.catalogueTree
    this.thematicDataTree = window.treeData.thematicDataTree
    this.cesiumDraw = null
    this.communityPrimitive = []
    this.imageLayer = null
    this.labelLayer = null
    this.otherLayers = {}
    this.cataLayers = {}
  },
  methods:{
    exportReport(){
      // 下载文件
      const link = document.createElement('a');
      link.style.display = 'none';
      // 设置下载地址
      link.setAttribute('href', window.exportPackageUrl);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    checkChange(){
      let checkNodes = this.$refs.thematicDataTree.getCheckedNodes()
      checkNodes = checkNodes.reverse()
      const allCheckLabels = checkNodes.map(item => item.realName ? item.realName : item.label)
      const otherLayKeys = Object.keys(this.otherLayers)
      otherLayKeys.forEach(item=>{
        if (!allCheckLabels.includes(item)){
          if (this.otherLayers[item].image){
            removeLayer(this.viewer,this.otherLayers[item].image)
          }
          if (this.otherLayers[item].label){
            removeLayer(this.viewer,this.otherLayers[item].label)
          }
          delete this.otherLayers[item]
        }
      })
      if (checkNodes.length === 0){
        return
      }
      checkNodes.forEach(item=>{
        if (item.serviceUrl || item.labelUrl){
          this.initServiceAndLabel(item,'otherLayers')
        }
      })
    },
    cataCheck(){
      const checkNodes = this.$refs.catalogueTree.getCheckedNodes()
      const allCheckLabels = checkNodes.map(item => item.realName ? item.realName : item.label)
      this.thematicDefaultCheck = allCheckLabels
      const cataLayKeys = Object.keys(this.cataLayers)
      cataLayKeys.forEach(item=>{
        if (!allCheckLabels.includes(item)){
          if (this.cataLayers[item].image){
            removeLayer(this.viewer,this.cataLayers[item].image)
          }
          if (this.cataLayers[item].label){
            removeLayer(this.viewer,this.cataLayers[item].label)
          }
          delete this.cataLayers[item]
        }
      })
      if (checkNodes.length === 0){
        return
      }
      checkNodes.forEach(item=>{
        if (item.serviceUrl || item.labelUrl){
          this.initServiceAndLabel(item,'cataLayers')
        }
      })
    },
    initServiceAndLabel(data,container){
      if (!data.realName){
        data.realName = data.label
      }
      if (!this[container][data.realName]){
        this[container][data.realName] = {}
      }
      if(data.serviceUrl){
        if (!this[container][data.realName].image){
          this[container][data.realName].image = addLayer(this.viewer,data.serviceUrl)
          this[container][data.realName].image.serviceUrl = data.serviceUrl
        }
      }
      if (data.labelUrl){
        if (!this[container][data.realName].label){
          this[container][data.realName].label = addLabelLayer(this.viewer,data.labelUrl)
          this[container][data.realName].label.serviceUrl = data.labelUrl
        }
      }
    },
    confirm(){
      const date = new Date(this.filterYear)
      const year = date.getFullYear()
      this.filterForm.filter = `${this.filterFields} ${this.calculateSymbol} ${year}`
      let node =  this.$refs.thematicDataTree.getCurrentNode()
      if (!node.children){
        node.children = []
      }
      const control = {
        otherDisplay:false,
        layers:[]
      }
      node.layer.forEach(item=>{
        control.layers.push({
          id: item,
          sqlFilterStr: this.filterForm.filter,
          display: true,
        })
      })
      node.children.push({
        ...this.filterForm,
        layer:node.layer,
        serviceUrl: node.serviceUrl + `&control=${encodeURIComponent(JSON.stringify(control))}`,
        labelUrl:node.labelUrl + `&control=${encodeURIComponent(JSON.stringify(control))}`,
        realName:node.label
      })
      this.thematicDataTree = JSON.parse(JSON.stringify(this.thematicDataTree))
      this.filterShow = false
    },
    setFiltering(data){
      this.filterForm = JSON.parse(JSON.stringify(FILTER_OBJ))
      this.filterShow = true
    },
    treeCheck(){
      const checkedKeys = this.$refs.communityTree.getCheckedKeys()
      this.communityPrimitive.forEach(item=>{
        if (checkedKeys.includes(item.name)){
          item.polyline.show = true
        } else {
          item.polyline.show = false
        }
      })
    },
    drawRange(){
      this.cesiumDraw.drawPlane((data)=>{
        this.showCommunity = true
        this.initRange()
      })
    },
    // 加载社区范围
    initRange(){
      let geojson = new Cesium.Geojson().read(choseSq)
      geojson.polygonArray.forEach(item=>{
        const entityOb = {
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray (item.geometry.pts),
            width: 2,
            material: Cesium.Color.fromCssColorString('#00ffff')
          }
        }
        const rangeLine = this.viewer.entities.add(entityOb);
        this.communityPrimitive.push({
          name:item.properties.CommunityN,
          polyline:rangeLine,
          entityOb:entityOb
        })
      })
      console.log(this.communityPrimitive);
    },
    cityChange(val){
      const {center} = this.$refs.cascader.getCheckedNodes(true)[0].data
      const coordinate = center.split(',')
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(coordinate[0],coordinate[1],
          2000
        ),
      })
    },
    // 获取城市信息
    async getCityProps(node, resolve) {
      let nodes = [];
      let keywords = ''
      if (node.level === 0) {
        keywords = '黄冈市'
      } else {
        keywords = node.value
      }
      let res = await axios.get(
        "https://restapi.amap.com/v3/config/district",
        {
          params: {
            keywords,
            subdistrict: 2,
            key: "4bb9d93c9b35ffdc9a5177d230394f23",
          },
        }
      );
      res.data.districts[0].districts.forEach((item) => {
        const leaf = !item.districts.length;
        nodes.push({ ...item,leaf });
      });
      resolve(nodes)
    },
    cesiumFinish(){
      this.viewer = this.Global.viewer
      const drawConfig = {
        borderColor: Cesium.Color.BLUE,
        borderWidth: 2,
        material:Cesium.Color.GREEN.withAlpha(0)
      }
      this.cesiumDraw = new Draw(this.viewer,drawConfig)
      // this.viewer.camera.setView({
      //   destination: Cesium.Cartesian3.fromDegrees(114.35977173421281,35.71087385794932,
      //     12000
      //   ),
      // })
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(114.87126489570386,30.43532669414297,
          12000
        ),
      })
    }
  },
  beforeDestroy(){
    removeLayer(this.viewer,this.imageLayer)
    removeLayer(this.viewer,this.labelLayer)
    this.cesiumDraw.removeEntity()
    this.viewer.entities.removeAll();
  }
};
</script>

<style lang="less" scoped>
.data-assembly{
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 16px;
  display: flex;
  .resource-catalog{
    width: 20%;
    height: 100%;
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .map-box{
    width: calc(80% - 10px);
    height: 100%;
    position:relative;
    .condition-box{
      background: #fff;
      padding: 5px;
      width:auto;
      height:auto;
      position:absolute;
      top: 5px;
      left: 5px;
      z-index: 20;
      .region-select{
        width: 100%;
        max-height: 600px;
        margin-top: 10px
      }
    }
    .legend{
      width:200px;
      position:absolute;
      bottom: 5px;
      right:5px;
      background: #fff;
      z-index: 30;
      padding: 10px;
      padding-top:0;
      .legend-item{
        width:70px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom:10px;
        img{
          width: 20px;
          height: 20px;
          margin-right: 10px
        }
      }
    }
  }
}
</style>